/**
 * 添加附件列表，支持同时选择多个附件
 * Created by csot.qhlinyunfu on 2018/12/24.
 */
Ext.define('App.view.common.file.FileFieldGrid', {
    extend: 'Ext.grid.Panel',
    xtype: 'fileFieldGrid',

    searchUrl: "",
    deleteUrl: "attachmentCtl/delById",
    downLoadUrl: '',
    allowBlank: true,
    height: 150,
    name: 'attachmentCommand',
    columnLines: true,
    _sumFileSize: 0, // 所有附件大小总和

    columns: [
        {
            text: '附件名称', dataIndex: 'fileName', flex: 1,minWidth:150,
            renderer: function (value, metaData, record) {
                if (record.get('businessId')) {
                    value = "<a style='color: #187bf7;text-decoration:underline;' href='" + record.get('filePath') + "' target='_blank' ><i class='fa fa-cloud-download' aria-hidden='false'></i>"
                        + record.get('fileName') + "</a>";
                }
                return value;
            }
        },
        {text: '上传时间', dataIndex: 'creationDate', width: 180},
        {
            text: '文件大小', dataIndex: 'fileSize', width: 180,
            renderer: function (value) {
                if (value) {
                    value = parseInt(value);
                    if (value < 1024 * 1024) {
                        value = Ext.Number.toFixed(value / 1024, 0) + 'KB';
                    } else {
                        value = Ext.Number.toFixed(value / (1024 * 1024), 0) + 'M';
                    }
                }
                return value;
            }
        },
        {
            text: '操作', dataIndex: 'handler', width: 150,align:'center',
            renderer: function (value, metaData, record) {
                if (record.get('businessId') && !this.readOnly) {
                    var id = record.get('id');
                    value = "<a style='background-color: #53c4f7;padding: 5px;color: white' href='#' ><i class='fa fa-trash-o' aria-hidden='false'></i>"
                        + "删除" + "</a>";
                }
                return value;
            }
        }
    ],

    store: {
        fields: ['fileName', 'creationDate', 'fileSize', 'handler']
    },

    initComponent: function () {
        this._setTools();
        this.callParent(arguments);
    },

    listeners: {
        beforecellclick: function (th, td, index, record, tr, rowIndex, e) {
            if (index == th.ownerGrid.getColumnByName('handler').fullColumnIndex
                && e.target.tagName == 'A' && td.textContent.trim()) {
                th.ownerGrid.deleteFile(record);
            }
        }
    },

    /**
     * 设置附件的url下载地址
     */
    _setFileData: function () {
        var me = this;
        var data = this.findAttByIdAndIdentify(this._recordId, this.name);
        me.getStore().add(data);
    },

    /**
     * 获取附件数据
     * @param id 当前数据id
     * @param attIdentify 当前附件标识
     * @returns {string} 附件对象数量JSON
     */
    findAttByIdAndIdentify: function (id, attIdentify) {
        var retdata = [];
        if (!id || !attIdentify) {
            return [];
        }
        Ext.Ajax.request({
            url: this.searchUrl,
            params: {businessId: id, fdKeyPrefix: attIdentify},
            async: false,
            method: 'GET',
            success: function (response) {
                var data = response.responseText;
                if (data) {
                    retdata = Ext.decode(data);
                }
            }
        });
        return retdata;
    },

    getColumnByName: function (name) {
        if (!name) {
            return;
        }
        var cols = this.getColumns();
        for (var i = 0; i < cols.length; i++) {
            if (cols[i].name == name || cols[i].dataIndex == name) {
                return cols[i];
            }
        }
    },

    /**
     * 删除附件数据
     */
    deleteFile: function (record) {
        var me = this;
        if (!record || !record.get('id')) {
            return;
        }

        Ext.MessageBox.confirm('删除确认', '确认要删除该附件吗?', function (isYes) {
            if (isYes == 'yes') {
                App.ux.Ajax.request({
                    url: me.deleteUrl,
                    params: {
                        ids: record.get('id')
                    },
                    method: 'POST',
                    success: function (response) {
                        me.getStore().remove(record);
                    }
                });
            }
        });
    },

    _reset: function (btn) {
        //附件对象重置
        var dockedItems = this.getDockedItems(), toolbar = dockedItems[0],
            toolbarItems = toolbar.items.items;
        while (toolbarItems.length > 2) {
            toolbar.remove(toolbarItems[1]);
        }
        toolbarItems[0].reset();

        //表格对象重置
        var store = this.getStore();
        if (store.getCount() > 0) {
            this._sumFileSize = 0;
            store.each(function (record) {
                if (!record.get('businessId')) {
                    store.remove(record);
                }
            });
        }
    },

    _setTools: function () {
        //如果当前可编辑列表是只读状态,不生成tool工具
        if (this.readOnly) {
            this.tools = [];
            return;
        }
        this.tbar = [
            {
                xtype: 'fileFields',
                maxWidth: 85,
                name: this.name,
                allowBlank: this.allowBlank
            },
            {
                xtype: 'container',
                items: [{
                    xtype: 'button',
                    name: 'r',
                    iconCls: "fa fa-undo",
                    text: '重置',
                    handler: function (btn) {
                        btn.up('grid')._reset(btn);
                    }
                }]
            }

        ];
    },

    _setAllowBlank: function (allowBlank) {
        var filefields = this.query('fileFields');
        for (var i = 0; i < filefields.length; i++) {
            filefields[i].setAllowBlank(allowBlank);
        }
    }
});